const state = {
  content: '',
  title: '',
  currentArticleId: null,
  isModified: false,
  autoSaveEnabled: true,
  wordCount: 0,
  previewMode: 'split', // split, preview, edit
  isFullscreen: false
}

const getters = {
  hasUnsavedChanges: (state) => state.isModified,
  
  currentArticle: (state) => {
    if (!state.currentArticleId && !state.title && !state.content) {
      return null
    }
    
    return {
      id: state.currentArticleId,
      title: state.title,
      content: state.content
    }
  },
  
  editorStats: (state) => {
    const content = state.content
    const wordCount = content.replace(/\s+/g, ' ').trim().split(' ').filter(word => word.length > 0).length
    const charCount = content.length
    const lineCount = content.split('\n').length
    
    return {
      wordCount,
      charCount,
      lineCount
    }
  }
}

const mutations = {
  SET_CONTENT(state, content) {
    state.content = content
    state.isModified = true
  },
  
  SET_TITLE(state, title) {
    state.title = title
    state.isModified = true
  },
  
  SET_CURRENT_ARTICLE_ID(state, id) {
    state.currentArticleId = id
  },
  
  SET_MODIFIED(state, modified) {
    state.isModified = modified
  },
  
  SET_AUTO_SAVE_ENABLED(state, enabled) {
    state.autoSaveEnabled = enabled
  },
  
  SET_PREVIEW_MODE(state, mode) {
    state.previewMode = mode
  },
  
  SET_FULLSCREEN(state, fullscreen) {
    state.isFullscreen = fullscreen
  },
  
  RESET_EDITOR(state) {
    state.content = ''
    state.title = ''
    state.currentArticleId = null
    state.isModified = false
  },
  
  LOAD_ARTICLE(state, article) {
    state.content = article.content || ''
    state.title = article.title || ''
    state.currentArticleId = article.id
    state.isModified = false
  }
}

const actions = {
  updateContent({ commit }, content) {
    commit('SET_CONTENT', content)
  },
  
  updateTitle({ commit }, title) {
    commit('SET_TITLE', title)
  },
  
  loadArticle({ commit }, article) {
    commit('LOAD_ARTICLE', article)
  },
  
  resetEditor({ commit }) {
    commit('RESET_EDITOR')
  },
  
  markAsSaved({ commit }) {
    commit('SET_MODIFIED', false)
  },
  
  togglePreviewMode({ commit, state }) {
    const modes = ['split', 'preview', 'edit']
    const currentIndex = modes.indexOf(state.previewMode)
    const nextIndex = (currentIndex + 1) % modes.length
    commit('SET_PREVIEW_MODE', modes[nextIndex])
  },
  
  toggleFullscreen({ commit, state }) {
    commit('SET_FULLSCREEN', !state.isFullscreen)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}